<template>
  <div>
    <div class="el-upload-model"><vue-tinymce v-if="visible" v-model="dataContent" :setting="setting" /></div>
  </div>
</template>
<script>
import { ossHost, aliyunOssApi, randomString, getSuffix } from '@/api/aliyun';
import axios from 'axios';

export default {
  name: 'EditTinymce',
  props: {
    content: {
      type: String,
      default: ''
    },
    visible: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      dataContent: this.content,
      ossHost: ossHost,
      setting: {
        menubar: false,
        toolbar:
          'preview | code searchreplace | undo redo | fullscreen | formatselect alignleft aligncenter alignright alignjustify | link unlink | numlist bullist | image media table | fontselect fontsizeselect forecolor backcolor | bold italic underline strikethrough hr | indent outdent indentabe lineheight | superscript subscript | formatpainter removeformat | emoticons',
        toolbar_drawer: 'sliding',
        quickbars_insert_toolbar: '',
        quickbars_selection_toolbar: 'removeformat | bold italic underline strikethrough | fontsizeselect forecolor backcolor | formatpainter removeformat',
        plugins: 'preview code searchreplace link image media table lists fullscreen quickbars lineheight hr emoticons formatpainter indentabe',
        language: 'zh_CN',
        height: 400,
        images_upload_url: `${process.env.VUE_APP_BASE_API_URL}/api/journal/admin/common/upload?dir=internal`,
        images_upload_handler: this.images_upload_handler,
        file_picker_callback: this.file_picker_callback,
        file_picker_types: 'media',
        font_formats:
          '宋体=SimSun;仿宋=FangSong;黑体=SimHei;楷体=KaiTi;隶书=LiSu;幼圆=YouYuan;微软雅黑	=Microsoft Yahei;Arial=arial;Arial Black=arial black;Comic Sans MS=comic sans ms;Courier New=courier new;Impact=impact;Terminal=terminal;Times New Roman=times new roman;Trebuchet MS=trebuchet ms;Verdana=verdana;'
      }
    };
  },
  computed: {},
  watch: {
    content(val) {
      this.dataContent = this.content;
    },
    dataContent(val) {
      this.$emit('onChange', val);
    }
  },
  methods: {
    async images_upload_handler(blobInfo, succFun, failFun) {
      var file = blobInfo.blob();
      const path = await this.upload(file);
      succFun(path);
    },
    async file_picker_callback(callback, value, meta) {
      const that = this;
      if (meta.filetype === 'file') {
        callback('mypage.html', { text: 'My text' });
      }
      // Provide image and alt text for the image dialog
      if (meta.filetype === 'image') {
        // callback('myimage.jpg', {alt: 'My alt text'});
      }
      // Provide alternative source and posted for the media dialog

      if (meta.filetype === 'media') {
        const filetype = '.mp4';
        // callback('movie.mp4', {source2: 'alt.ogg', poster: 'image.jpg'});
        var input = document.createElement('input');
        input.setAttribute('type', 'file');
        input.setAttribute('accept', filetype);
        input.click();
        input.onchange = async function() {
          alert('视频上传中，请勿关闭窗口，上传成功后会弹出上传成功提示框');
          var file = this.files[0];
          // console.log(file.name, file);
          const path = await that.upload(file);
          // callback('movie.mp4', {source2: 'alt.ogg', poster: 'image.jpg'});
          // console.log('file path', path)
          if (path && path !== '') {
            alert('视频上传成功');
          }
          callback(path);
        };
      }
    },
    upload(file) {
      return new Promise(resolve => {
        aliyunOssApi('internal')
          .then(res => {
            if (res.code === 0) {
              // console.log("><<<<<<<<<<<<<<", randomString(10), file.name)
              let picName = randomString(10) + getSuffix(file.name);
              let keyValue = res.data.dir + picName;
              // 注意formData里append添加的键的大小写
              let formData = new FormData();
              formData.append('name', file.name); // 文件名称
              formData.append('key', keyValue); // 存储在oss的文件路径
              formData.append('OSSAccessKeyId', res.data.accessid); // //accessKeyId
              formData.append('policy', res.data.policy); // policy
              formData.append('Signature', res.data.signature); // 签名
              formData.append('success_action_status', 200);
              formData.append('file', file, file.name); // 如果是base64文件，那么直接把base64字符串转成blob对象进行上传即可

              axios
                .post(this.ossHost, formData, {
                  headers: {
                    'Content-Type': 'multipart/form-data'
                  }
                  // 图片上传进度
                  // onUploadProgress: progressEvent => {
                  //   this.progressPercent = Math.floor((progressEvent.loaded * 100) / progressEvent.total);
                  // }
                })
                .then(rep => {
                  if (rep.status === 200) {
                    console.log('Uploaded successfully&&&', this.ossHost + keyValue);
                    resolve(this.ossHost + keyValue);
                  }
                  resolve(rep);
                })
                .catch(err => {
                  console.log(err);
                });
            }
          })
          .catch(err => {
            console.log(err);
          });
      });
    }
  }
};
</script>

<style scoped>
.avatar {
  width: 146px;
  height: 146px;
}
</style>
